
import React, { useEffect, useState } from 'react'
import style from './index.module.scss'
import { Form, Input, Upload, message, Button, Select, Radio } from 'antd'
import { PlusOutlined } from '@ant-design/icons'
import { addPublic } from '@/common/api'
import { getLs } from '@/common/common'
import { connect } from 'react-redux'
import { asyncAddContent } from '@/store/actions'
const tagList = [
  { text: '教育', value: 'education' },
  { text: '运动', value: 'exercise' },
  { text: "旅行" , value:"travel"},
  {text:"穿搭",value:"attire"},
  { text: '美食', value: 'food' },
  { text: '影视', value: 'movie' },
  { text: '游戏', value: 'game' },
  { text: '其他', value: 'other' },
]
const { TextArea } = Input;
function Public() {
  const [fileList, setFileList] = useState([])
  const [form] = Form.useForm(); // 创建表单实例 
   const [userInfo, setInfo] = useState({})

  useEffect(() => {
    const _userInfo = getLs('userInfo')
    setInfo(_userInfo)
  }, [])
  const handleChange = async ({ fileList: newFileList, file }) => {
    const isJpgOrPng = file.type === 'image/jpeg' || file.type === 'image/png';
    if (!isJpgOrPng) {
      return false
    }
    if (newFileList.length === 0) {
      form.setFieldsValue({imgList:undefined})
      setFileList(newFileList);
      form.validateFields(); // 强制重新校验
      return
    }
    setFileList(newFileList);
    form.setFieldsValue({imgList:newFileList})
    console.log(form.getFieldsValue());
    
  }
  const uploadButton = (
    <button
      style={{
        border: 0,
        background: 'none',
      }}
      type="button"
    >
      <PlusOutlined />
      <div
        style={{
          marginTop: 8,
        }}
      >
        点击上传
      </div>
    </button>
  );
  const beforeUpload = (file) => {
    const isJpgOrPng = file.type === 'image/jpeg' || file.type === 'image/png';
    if (!isJpgOrPng) {
      message.error('你只能上传JPG/PNG 的文件!');
      return false
    }
    return false
  };
  const AddPublic = async () => {
    try {
      const formData = new FormData()
      const isValid = await form.validateFields()
      const timer = Math.floor(Date.now() / 1000)
      if (isValid) {
        const formObj = form.getFieldValue()
        fileList.forEach(ele => {
          formData.append('imgList', ele.originFileObj)
        })
        for (const key in formObj) {
          formData.append(key, formObj[key])
        }
        formData.append('userId', userInfo._id)
        formData.append('time', timer)
      }
      const RES = await addPublic(formData)
      if (RES.code === 200) {
        message.success(RES.msg)
      }
    } catch (error) {
      return
    }
  }
  return (
    <div className={style.Public}>
      <div className={style.smallDiv}> 
        <div className={style.title}>
          <h2>发布图文</h2>
        </div>
        <Form
          form={form}
        >
          <Form.Item name='imgList' rules={[{
            required:true,message:"请上传图片!"
          }]}>
            <p className={style.title} style={{ marginBottom: "10px" }}>图文编辑 <span style={{ color: "#a5a5a5" }}>({fileList.length}/5)</span></p>
            <Upload
              listType="picture-card"
              fileList={fileList}
              beforeUpload={beforeUpload}
              onChange={handleChange}
            >
              {fileList.length < 5 && uploadButton}
            </Upload>
          </Form.Item>
          <div className={style.content}>
          <p className={style.title} style={{ marginBottom: "10px" }}>正文内容</p>
            <Form.Item name="title" rules={[{ required: true ,message:'请输入标题内容'}]}>
              <Input placeholder="请输入标题"
                count={{
                  show: true,
                  max: 30,
                }} />
            </Form.Item>
            <Form.Item name="text" rules={[{ required: true ,message:'请输入文本内容'}]}>
              <TextArea
                showCount
                maxLength={200} 
                placeholder="请输入文本内容"
                style={{ height: 200, resize: 'none' }}
              />
            </Form.Item>
          </div>
          <div className={style.selectRadio}>
            <Form.Item
              label="选择标签"
              name="tag"
              initialValue="other"
              rules={[
                {
                  required: true,
                  message: '请选择标签',
                },
              ]}
            >
              <Select
                style={{width:120}}
              >
                {tagList.map(ele => {
                  return <Select.Option  value={ele.value} key={ele.value}>{ele.text}</Select.Option>
                })}
              </Select>
            </Form.Item>
            <Form.Item
              label="可见范围"
              initialValue={1}
              name="area"
            >
              <Radio.Group>
                <Radio value={1}>公开</Radio>
                <Radio value={0}>私密</Radio>
              </Radio.Group>
            </Form.Item>
          </div>
          <Form.Item>
            <Button type='primary' onClick={AddPublic}>发布</Button>
          </Form.Item>
        </Form>
      </div>
    </div>
  )
}

export default connect(null, dispatch => {
  return {
    addPublic:(val)=>asyncAddContent(dispatch,val)
  }
})(Public)